<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Student;
use App\Models\Teacher;
use Illuminate\Database\Seeder;
use Illuminate\Http\Request;

/**
 * Class StudentController
 * @package App\Http\Controllers\Admin
 * User: ZengMingYong
 * Date: 2020/7/2
 * Time: 5:19
 * 学生账号
 */
class StudentController extends CommonController
{

    public function index()
    {
        //withTrashed 包换软删除
        $data=Student::orderBy('id','desc')->paginate($this->page);
        return view('admin.student.index',compact('data'));
    }


    public function create()
    {
        return view('admin.student.create');
    }

    public function store(Request $request)
    {
        $post=$this->validate($request,[
            'name'=>'required',
            'password'=>'required|confirmed',
            'phone' =>'required|phone',
            'email'=>'required|email',
            'sex'=>'required',
            'class_name'=>'required',
        ]);
        $post['student_code']=Student::max('student_code');
        $post['student_code']=$post['student_code']+1;
       Student::create($post);
       return redirect(route('admin.student.index'))->with(['error'=>'账号'.$post['student_code'].'注册成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        //
    }


    public function edit(Student $student)
    {
        return view('admin.student.edit',['student'=>$student]);
    }

    public function update(Request $request, Student $student)
    {
        $post=$this->validate($request,[
            'name'=>'required',
            'sex'=>'required',
            'class_name'=>'required',
        ]);
        $student->update($post);
        return redirect(route('admin.student.index'))->with(['error'=>'斜杠成功']);
    }

    /**
     * @param Student $student
     * @return array
     * @throws \Exception
     */
    public function destroy(Student $student)
    {
         $student->delete();
        return ['status'=>0,'msg'=>'删除成功'];
    }
    //批量生成学号
    //视图
    public function batch(){
        return view('admin.student.batch');
    }
    //批量生成学号
    //处理
    public function batchs(Request $request)
    {
        $post=$this->validate($request,[
            'name'=>'required',
            'password'=>'required|confirmed',
            'phone' =>'required|phone',
            'email'=>'required|email',
            'sex'=>'required',
            'class_name'=>'required',
            'num'=>'required'
        ]);
        $info[0]=$request->only(['name','password','phone','email','sex','class_name']);
        //获取最大的学号
        $student_code=Student::max('student_code');
        //循环数组
        for ($x=0; $x<=$request->get('num'); $x++) {
            $info[$x]=$info[0];
            $info[$x]['student_code']=$x+$student_code+1;
        }
       $bool= Student::insert($info);
        if ($bool){
            //withTrashed 包换软删除
            $data=Student::orderBy('id','desc')
                ->whereBetween('student_code',[$student_code+1,$student_code+$request->get('num')])
                ->paginate($request->get('num'));
            return view('admin.student.index',compact('data'))->with(['error'=>'批量生成账号成功']);
        }
    }
    //导出学生信息
    public function info(Request $request){
        $class_name=$request->input('class_name');
        $data=Student::where('class_name',$class_name)
        ->paginate(100);
        if ($request->isMethod('POST')){
            //生成excel表格
            $excel=Student::where('class_name',$class_name)
                ->get(['name','student_code','phone','email'])
                ->toArray();
            if ($excel==null){
                return redirect(route('admin.student.info',compact('data')))->with(['error'=>'没有数据']);
            }
            $title = ['姓名', '学号','手机号','邮箱'];
            // Create new Spreadsheet object
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            //设置宽度自适应
            $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);

            // 方法一，使用 setCellValueByColumnAndRow
            //表头
            //设置单元格内容
            foreach ($title as $key => $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
            }
            $row = 2; // 从第二行开始
            foreach ($excel as $item) {
                $column = 1;
                foreach ($item as $value) {
                    // 单元格内容写入
                    $sheet->setCellValueByColumnAndRow($column, $row, $value);
                    $column++;
                }
                $row++;
            }
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            // Redirect output to a client’s web browser (Xlsx)
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="'.$class_name.'.Xlsx"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');
            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');//'php://output'
            exit;
        }

        return view('admin.student.info',compact('data'));

    }
    //导出学生信息处理
    public function infos(){

    }
}
